package com.zjw.controller;


import com.zjw.entity.po.User;
import com.zjw.service.UserService;
import com.zjw.utils.FileUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/importExcel")
    @ResponseBody
    public Integer importExcel(@RequestParam("file") MultipartFile file){
//        String filePath = "/users/海贼王.xls";
        //解析excel，
//        List<Person> personList = FileUtils.importExcel(filePath,1,1,Person.class);
        //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
        List<User> userList = FileUtil.importExcel(file, 1, 1, User.class);
        System.out.println("导入数据一共【"+userList.size()+"】行");
        userList.forEach(System.out::println);
        if(CollectionUtils.isEmpty(userList)){
            return 0;
        }
        List<User> list = userService.getUserList();
//        list.forEach(System.out::println);
        List<User> newList = new ArrayList<>();
        for (User user : userList) {
            for (int i = 0; i < list.size();i++) {
                if(user.getId().equals(list.get(i).getId())){
                    System.out.println(user);
                    break;
                }
                if(i == list.size()-1){
                    newList.add(user);
                }
            }
        }
        newList.forEach(System.out::println);
        return userService.insertSelective(newList);

        //TODO 保存数据库
    }
}
